package pikes.peak;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.springframework.web.servlet.support.RequestContext;

import pikes.html.xhtml.table.TR;
import pikes.html.xhtml.table.TableCell;
import pikes.util.Util;

public class CellCollection implements RequestProperty<TR> {

	private Collection<RequestProperty<TableCell>> cellProviders = new LinkedList<RequestProperty<TableCell>>();

	private RowDecorator rowDecorator = RowDecorator.NULL_DECORATOR;

	public CellCollection() {

	}

	public CellCollection(Collection<RequestProperty<TableCell>> cellProviders) {
		this.cellProviders = cellProviders;
	}

	public CellCollection(RowDecorator rowDecorator) {
		this.rowDecorator = rowDecorator;
	}

	final public TR getValue(Map model, RequestContext requestContext) throws Exception {

		if (!Util.isEmpty(cellProviders)) {
			List<TableCell> tableCells = new LinkedList<TableCell>();

			for (RequestProperty<TableCell> tableCellProvider : cellProviders) {
				TableCell tableCell = tableCellProvider.getValue(model, requestContext);
				if (tableCell != null) {
					tableCells.add(tableCell);
				}
			}

			if (!tableCells.isEmpty()) {
				Iterator<TableCell> iTableCells = tableCells.iterator();

				TableCell tableCell = iTableCells.next();

				TR tr = new TR(tableCell);

				while (iTableCells.hasNext()) {
					tableCell = iTableCells.next();
					tr.add(tableCell);
				}

				rowDecorator.decorateRow(tr, model, requestContext);

				return tr;
			}
		}
		return null;
	}

	public void add(RequestProperty<TableCell> objectProvider) {
		if (objectProvider != null) {
			cellProviders.add(objectProvider);
		}
	}

}
